<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="utf-8">
    <meta name="keywords" content="Vue源码系列1-new Vue过程中发生了什么, HTML,CSS,JavaScript,JQuery,React,Vue.js等">
    <meta name="description" content="别做一个Vue api调用师">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Vue源码系列1-new Vue过程中发生了什么 | zihao blog</title>
    <link rel="icon" type="image/png" href="/pride-blog/favicon.png">

    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/css/my.css">

    <script src="/pride-blog/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.3.0"><link rel="stylesheet" href="/pride-blog/css/prism-tomorrow.css" type="text/css"><!-- hexo-inject:begin --><!-- hexo-inject:end --></head>




<body>
    <!-- hexo-inject:begin --><!-- hexo-inject:end --><header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/pride-blog/" class="waves-effect waves-light">
                    
                    <img src="/pride-blog/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">zihao blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/pride-blog/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/pride-blog/categories/CSS/" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/pride-blog/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/pride-blog/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">zihao blog</div>
        <div class="logo-desc">
            
            别做一个Vue api调用师
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/pride-blog/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/pride-blog/categories/CSS/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/pride-blog/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/pride-blog/medias/featureimages/14.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Vue源码系列1-new Vue过程中发生了什么</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/pride-blog/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/pride-blog/tags/Vue%E6%BA%90%E7%A0%81/">
                                <span class="chip bg-color">Vue源码</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/pride-blog/categories/Vue%E6%BA%90%E7%A0%81/" class="post-category">
                                Vue源码
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-06-09
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h3 id="Vue-源码系列-1"><a href="#Vue-源码系列-1" class="headerlink" title="Vue 源码系列 1"></a>Vue 源码系列 1</h3><p>今天是阅读 Vue 源码的第三天,虽然配合文章和视频第二天的看了 3 遍,还是没看懂;但是还是要强迫自己记录点东西了;(悲伤辣么大)</p>
<ul>
<li><ol>
<li> vue 源码——结构</li>
</ol>
</li>
</ul>
<pre class=" language-javaScript"><code class="language-javaScript">├── benchmarks                  性能、基准测试
├── dist                        构建打包的输出目录
├── examples                    案例目录
├── flow                        flow 语法的类型声明
├── packages                    一些额外的包，比如：负责服务端渲染的包 vue-server-renderer、配合 vue-loader 使用的的 vue-template-compiler，还有 weex 相关的
│   ├── vue-server-renderer
│   ├── vue-template-compiler
│   ├── weex-template-compiler
│   └── weex-vue-framework
├── scripts                     所有的配置文件的存放位置，比如 rollup 的配置文件
├── src                         vue 源码目录
│   ├── compiler                编译器
│   ├── core                    运行时的核心包
│   │   ├── components          全局组件，比如 keep-alive
│   │   ├── config.js           一些默认配置项
│   │   ├── global-api          全局 API，比如熟悉的：Vue.use()、Vue.component() 等
│   │   ├── instance            Vue 实例相关的，比如 Vue 构造函数就在这个目录下
│   │   ├── observer            响应式原理
│   │   ├── util                工具方法
│   │   └── vdom                虚拟 DOM 相关，比如熟悉的 patch 算法就在这儿
│   ├── platforms               平台相关的编译器代码
│   │   ├── web
│   │   └── weex
│   ├── server                  服务端渲染相关
├── test                        测试目录
├── types                       TS 类型声明

</code></pre>
<ul>
<li><ol start="2">
<li>Vue 初始化过程<br><strong>面试题:new Vue()过程中发生了什么?</strong></li>
</ol>
<ul>
<li>2.1 首先我们要先找到 Vue 的构造函数,因此我们先写一个例子,去找 Vue 构造函数;</li>
</ul>
<pre class=" language-html"><code class="language-html"><span class="token doctype">&lt;!DOCTYPE html></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>html</span> <span class="token attr-name">lang</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>en<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>head</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>meta</span> <span class="token attr-name">charset</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>UTF-8<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>title</span><span class="token punctuation">></span></span>Vue 源码解读<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>title</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>head</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>app<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token entity" title="&#123;">&amp;#123;</span><span class="token entity" title="&#123;">&amp;#123;</span> msg <span class="token entity" title="&#125;">&amp;#125;</span><span class="token entity" title="&#125;">&amp;#125;</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>../dist/vue.js<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token script language-javascript"></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span><span class="token punctuation">></span></span><span class="token script language-javascript">
      <span class="token keyword">debugger</span><span class="token punctuation">;</span>
      <span class="token keyword">new</span> <span class="token class-name">Vue</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        el<span class="token punctuation">:</span> <span class="token string">"#app"</span><span class="token punctuation">,</span>
        data<span class="token punctuation">:</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
          msg<span class="token punctuation">:</span> <span class="token string">"hello vue"</span><span class="token punctuation">,</span>
        <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span>
      <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>html</span><span class="token punctuation">></span></span></code></pre>
<p>在浏览器中打开控制台,进行端点调试,找到 Vue 构造函数是在<code>/src/core/instance/index.js</code></p>
</li>
<li><ol start="3">
<li>Vue 构造函数<br><code>目录: /src/core/instance/index.js</code></li>
</ol>
</li>
</ul>
<pre class=" language-javaScript"><code class="language-javaScript">import &#123; initMixin &#125; from './init'

// Vue 构造函数
function Vue (options) &#123;
  // 调用 Vue.prototype._init 方法，该方法是在 initMixin 中定义的
  this._init(options)
&#125;

// 定义 Vue.prototype._init 方法
initMixin(Vue)

export default Vue
</code></pre>
<p>发现整个 Vue 构造函数中只调用了<code>this._init方法</code>;</p>
<ul>
<li>3.1 Vue.prototype._init 方法<br><code>目录:/src/core/instance/init.js</code></li>
</ul>
<pre class=" language-javaScript"><code class="language-javaScript"> // 定义 Vue.prototype.\_init 方法
 // @param &#123;_&#125; Vue Vue 构造函数
 export function initMixin (Vue: Class<Component>) &#123;
 // 负责 Vue 的初始化过程
 Vue.prototype.\_init = function (options?: Object) &#123;
 // vue 实例
 const vm: Component = this
 // 每个 vue 实例都有一个 \_uid，并且是依次递增的
 vm.\_uid = uid++
     // a flag to avoid this being observed
     vm._isVue = true
     // 处理组件配置项
     if (options && options._isComponent) &#123;
       // 子组件走这里:性能优化
       // 将组件配置对象上的一些深层次属性放到 vm.$options 选项中，以提高代码的执行效率
       initInternalComponent(vm, options)
     &#125; else &#123;
         // 根组件走这里:选项合并,将全局的配置项合并到根组件的局部配置上
         // 初始化根组件时走这里，合并 Vue 的全局配置到根组件的局部配置，比如 Vue.component 注册的全局组件会合并到 根实例的 components 选项中
        // 至于每个子组件的选项合并则发生在两个地方：
        // 1、Vue.component 方法注册的全局组件在注册时做了选项合并
        // 2、&#123; components: &#123; xx &#125; &#125; 方式注册的局部组件在执行编译器生成的 render 函数时做了选项合并，包括根组件中的 components 配置
       vm.$options = mergeOptions(
         resolveConstructorOptions(vm.constructor),
         options || &#123;&#125;,
         vm
       )
     &#125;
     /* istanbul ignore else */
     if (process.env.NODE_ENV !== 'production') &#123;
       // 设置代理，将 vm 实例上的属性代理到 vm._renderProxy
       initProxy(vm)
     &#125; else &#123;
       vm._renderProxy = vm
     &#125;
     // expose real self
     vm._self = vm
     <!-- 整个初始化的核心 -->
     // 初始化组件实例关系属性，比如 $parent、$children、$root、$refs 等
     initLifecycle(vm)
     // 初始化组件上的自定义事件，这里需要注意一点，所以我们在 <comp @click="handleClick" /> 上注册的事件，监听者不是父组件，
     // 而是子组件本身，也就是说事件的派发和监听者都是子组件本身，和父组件无关
     initEvents(vm)
     // 初始化插槽，得到 vm.$slot，处理渲染函数，得到 vm.$createElement 方法，即 h 函数
     initRender(vm)
     // 调用 beforeCreate 钩子函数
     callHook(vm, 'beforeCreate')
     // 初始化inject 配置项，得到 result[key] = val 形式的配置对象，然后对结果数据进行响应式处理，并代理每个 key 到 vm 实例
     initInjections(vm) // resolve injections before data/props
     // 数据响应式的重点，处理 props、data、computed、watch、methods、
     initState(vm)
     // 解析组provide 配置项，将其挂载到 vm._provided 属性上
     initProvide(vm) // resolve provide after data/props
     // 调用 created 钩子函数
     callHook(vm, 'created')
     // 如果发现配置项上有 el 选项，则自动调用 $mount 方法，也就是说有了 el 选项，就不需要再手动调用 $mount，反之，没有 el 则必须手动调用 $mount
     if (vm.$options.el) &#123;
       // 调用 $mount 方法，进入挂载阶段
       vm.$mount(vm.$options.el)
     &#125;

 &#125;
 &#125;</code></pre>
<ul>
<li>3.2 resolveConstructorOptions<br><code>目录:/src/core/instance/init.js</code></li>
</ul>
<pre class=" language-javaScript"><code class="language-javaScript">
/\*\*

// - 从组件构造函数中解析配置对象 options，并合并基类选项
// - @param &#123;\*&#125; Ctor
// - @returns
  \*/
  export function resolveConstructorOptions (Ctor: Class<Component>) &#123;
  // 配置项目
  let options = Ctor.options
  if (Ctor.super) &#123;
  // 存在基类，递归解析基类构造函数的选项
  const superOptions = resolveConstructorOptions(Ctor.super)
  const cachedSuperOptions = Ctor.superOptions
  if (superOptions !== cachedSuperOptions) &#123;
  // 说明基类构造函数选项已经发生改变，需要重新设置
  Ctor.superOptions = superOptions
  // 检查 Ctor.options 上是否有任何后期修改/附加的选项（＃4976）
  const modifiedOptions = resolveModifiedOptions(Ctor)
  // 如果存在被修改或增加的选项，则合并两个选项
  if (modifiedOptions) &#123;
  extend(Ctor.extendOptions, modifiedOptions)
  &#125;
  // 选项合并，将合并结果赋值为 Ctor.options
  options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
  if (options.name) &#123;
  options.components[options.name] = Ctor
  &#125;
  &#125;
  &#125;
  return options
  &#125;
</code></pre>
<ul>
<li>3.3 resolveModifiedOptions<br><code> 目录:/src/core/instance/init.js</code></li>
</ul>
<pre class=" language-javaScript"><code class="language-javaScript">
// 解析构造函数选项中后续被修改或者增加的选项
function resolveModifiedOptions (Ctor: Class<Component>): ?Object &#123;
let modified
// 构造函数选项
const latest = Ctor.options
// 密封的构造函数选项，备份
const sealed = Ctor.sealedOptions
// 对比两个选项，记录不一致的选项
for (const key in latest) &#123;
if (latest[key] !== sealed[key]) &#123;
if (!modified) modified = &#123;&#125;
modified[key] = latest[key]
&#125;
&#125;
return modified
&#125;
</code></pre>
<ul>
<li>3.4 mergeOptions<br><code>目录:/src/core/util/options.js</code></li>
</ul>
<pre class=" language-javaScript"><code class="language-javaScript">
// 合并两个选项，出现相同配置项时，子选项会覆盖父选项的配置
export function mergeOptions (
parent: Object,
child: Object,
vm?: Component
): Object &#123;
if (process.env.NODE_ENV !== 'production') &#123;
checkComponents(child)
&#125;

if (typeof child === 'function') &#123;
child = child.options
&#125;

// 标准化 props、inject、directive 选项，方便后续程序的处理
normalizeProps(child, vm)
normalizeInject(child, vm)
normalizeDirectives(child)

// 处理原始 child 对象上的 extends 和 mixins，分别执行 mergeOptions，将这些继承而来的选项合并到 parent
// mergeOptions 处理过的对象会含有 \_base 属性
if (!child.\_base) &#123;
if (child.extends) &#123;
parent = mergeOptions(parent, child.extends, vm)
&#125;
if (child.mixins) &#123;
for (let i = 0, l = child.mixins.length; i < l; i++) &#123;
parent = mergeOptions(parent, child.mixins[i], vm)
&#125;
&#125;
&#125;

const options = &#123;&#125;
let key
// 遍历 父选项
for (key in parent) &#123;
mergeField(key)
&#125;

// 遍历 子选项，如果父选项不存在该配置，则合并，否则跳过，因为父子拥有同一个属性的情况在上面处理父选项时已经处理过了，用的子选项的值
for (key in child) &#123;
if (!hasOwn(parent, key)) &#123;
mergeField(key)
&#125;
&#125;

// 合并选项，childVal 优先级高于 parentVal
function mergeField (key) &#123;
// strats = Object.create(null)
const strat = strats[key] || defaultStrat
// 值为如果 childVal 存在则优先使用 childVal，否则使用 parentVal
options[key] = strat(parent[key], child[key], vm, key)
&#125;
return options
&#125;
</code></pre>
<ul>
<li>3.5 initInjections<br><code>目录:/src/core/instance/inject.js</code></li>
</ul>
<pre class=" language-javaScript"><code class="language-javaScript">
// 初始化 inject 配置项
// 1、得到 result[key] = val
// 2、对结果数据进行响应式处理，代理每个 key 到 vm 实例
export function initInjections (vm: Component) &#123;
// 解析 inject 配置项，然后从祖代组件的配置中找到 配置项中每一个 key 对应的 val，最后得到 result[key] = val 的结果
const result = resolveInject(vm.$options.inject, vm)
  // 对 result 做 数据响应式处理，也有代理 inject 配置中每个 key 到 vm 实例的作用。
  // 不不建议在子组件去更改这些数据，因为一旦祖代组件中 注入的 provide 发生更改，你在组件中做的更改就会被覆盖
  if (result) &#123;
    toggleObserving(false)
    Object.keys(result).forEach(key => &#123;
      /* istanbul ignore else */
      if (process.env.NODE_ENV !== 'production') &#123;
        defineReactive(vm, key, result[key], () => &#123;
          warn(
            `Avoid mutating an injected value directly since the changes will be ` +
            `overwritten whenever the provided component re-renders. ` +
            `injection being mutated: "$&#123;key&#125;"`,
vm
)
&#125;)
&#125; else &#123;
defineReactive(vm, key, result[key])
&#125;
&#125;)
toggleObserving(true)
&#125;
&#125;
</code></pre>
<ul>
<li>3.6 resolveInject<br><code>/src/core/instance/inject.js</code></li>
</ul>
<pre class=" language-javaScript"><code class="language-javaScript">// 解析 inject 配置项，从祖代组件的 provide 配置中找到 key 对应的值，否则用 默认值，最后得到 result[key] = val
// inject 对象肯定是以下这个结构，因为在 合并 选项时对组件配置对象做了标准化处理
  export function resolveInject (inject: any, vm: Component): ?Object &#123;
  if (inject) &#123;
  // inject is :any because flow is not smart enough to figure out cached
  const result = Object.create(null)
  // inject 配置项的所有的 key
  const keys = hasSymbol
  ? Reflect.ownKeys(inject)
  : Object.keys(inject)

      // 遍历 key
      for (let i = 0; i < keys.length; i++) &#123;
        const key = keys[i]
        // 跳过 __ob__ 对象
        // #6574 in case the inject object is observed...
        if (key === '__ob__') continue
        // 拿到 provide 中对应的 key
        const provideKey = inject[key].from
        let source = vm
        // 遍历所有的祖代组件，直到 根组件，找到 provide 中对应 key 的值，最后得到 result[key] = provide[provideKey]
        while (source) &#123;
          if (source._provided && hasOwn(source._provided, provideKey)) &#123;
            result[key] = source._provided[provideKey]
            break
          &#125;
          source = source.$parent
        &#125;
        // 如果上一个循环未找到，则采用 inject[key].default，如果没有设置 default 值，则抛出错误
        if (!source) &#123;
          if ('default' in inject[key]) &#123;
            const provideDefault = inject[key].default
            result[key] = typeof provideDefault === 'function'
              ? provideDefault.call(vm)
              : provideDefault
          &#125; else if (process.env.NODE_ENV !== 'production') &#123;
            warn(`Injection "$&#123;key&#125;" not found`, vm)
          &#125;
        &#125;
      &#125;
      return result

  &#125;
  &#125;
</code></pre>
<ul>
<li>3.7 initProvide<br><code>目录:/src/core/instance/inject.js</code></li>
</ul>
<pre class=" language-javaScript"><code class="language-javaScript">// 解析组件配置项上的 provide 对象，将其挂载到 vm._provided 属性上
export function initProvide (vm: Component) &#123;
  const provide = vm.$options.provide
  if (provide) &#123;
    vm._provided = typeof provide === 'function'
      ? provide.call(vm)
      : provide
  &#125;
&#125;

</code></pre>
<h4 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h4><p><code>Vue 的初始化过程（new Vue(options)）都做了什么？</code></p>
<ul>
<li><p>initInternalComponent 方法:处理组件一些神层次的配置项</p>
<ul>
<li><p>初始化根组件时进行了选项合并操作，将全局配置合并到根组件的局部配置上<code>(把组件依赖于父组件的props/listeners挂载到options上,方便子组件调用)</code></p>
</li>
<li><p>初始化每个子组件时做了一些性能优化，将组件配置对象上的一些深层次属性放到 vm.$options 选项中，以提高代码的执行效率<code>(指定组件$options 原型)</code></p>
</li>
</ul>
</li>
<li><p>initLifeCycle 方法:初始化组件实例的关系属性，比如 $parent、$children、$root、$refs 等</p>
</li>
<li><p>initEvents 方法:处理组件上的一些自定义事件;(比如&lt;comp @click=”handleClick” /&gt;组件上的 handleClick 事件)</p>
</li>
<li><p>initRender 方法:初始化插槽信息;</p>
</li>
<li><p>callHook(vm, ‘beforeCreate’):调用 beforeCreate 生命周期钩子函数</p>
</li>
<li><p>initInject 方法:初始化组件的 inject 配置项，得到 ret[key] = val 形式的配置对象，然后对该配置对象进行响应式处理，并代理每个 key 到 vm 实例上</p>
</li>
<li><p>initSate 方法:数据响应式的核心处理，处理 props、data、computed、watch、methods、 等选项</p>
</li>
<li><p>initProvide 方法:解析组件配置项上的 provide 对象，将其挂载到 vm._provided 属性上</p>
</li>
<li><p>callHook(vm, ‘created’):调用 created 钩子函数</p>
</li>
</ul>
<p>如果发现配置项上有 el 选项，则自动调用 $mount 方法，也就是说有了 el 选项，就不需要再手动调用 $mount 方法，反之，没提供 el 选项则必须调用 $mount</p>
<p>接下来则进入挂载阶段</p>
<p>initInternalComponent - 处理组件的配置项<br>initLifeCycle-处理组件的关系属性:$parent $children $refs 等<br>initEvents - :处理组件上的自定义事件 比如子组件上定义的&lt;children @updateData=”updateData”&gt;</children> updateData 自定义事件<br>initRender:初始化插槽信息<br>callhook(‘beforeCreate’)生命周期钩子函数<br>initInject:初始化 inject 配置项<br>initState：数据响应式处理,处理 props、data、computed、watch、methods<br>initProvide:处理 provide 配置项<br>callhook(‘created’)生命周期钩子函数<br>进入挂载阶段</p>
<p>initInternalComponent：处理组件的一些配置项<br>initLifeCycle:初始化组件的一些关系属性:$parent $children $ refs<br>initEvents:初始化组件的一些自定义事件<br>initRender:初始化组件的插槽信息<br>callhook(‘beforeCreate’)生命周期钩子函数<br>initInject:初始化 inject 配置项<br>initState：数据响应式处理：处理 props/data/computed/watch/methods<br>initProvide：初始化 provide 配置项<br>callhook(‘created’)生命周期钩子函数<br>进入挂载阶段</p>
<p>2021.8.2 复习补充在上面了;</p>
<p>2021.8.26</p>
<h4 id="Vue-初始化过程中做了什么？"><a href="#Vue-初始化过程中做了什么？" class="headerlink" title="Vue 初始化过程中做了什么？"></a>Vue 初始化过程中做了什么？</h4><ul>
<li>initInternalComponents():初始化根组件并合并选项<ul>
<li>指定组件$options 原型</li>
<li>把组件依赖于父组件的 props/liseners 也挂载到 options 上</li>
<li>扩展:$options:是用来获取 data 外面定义的 data 和方法</li>
</ul>
</li>
<li>initLifeCycle():初始化组件实例的关系属性：如$parent / $children / $props / $refs 等</li>
<li>initEvent():初始化组件实例上的自定义事件</li>
<li>initRender():初始化插槽信息</li>
<li>callhook(‘beforeCreate’,vm):触发 beforeCreate 钩子函数</li>
<li>initState():初始化 data/props/methods/computed/watch</li>
<li>initInjection():初始化 inject 配置项</li>
<li>initProvide():初始化 provide 配置项</li>
<li>callhook(‘created’,vm):触发 created 钩子函数</li>
<li>触发$mouted 进入挂载阶段</li>
</ul>
<p>2022.06.21复习<br>new Vue()过程中做了哪些事情？<br>new Vue()的初始化methods是this._init();里面具体做了哪些事情？</p>
<ol>
<li>initLifeCycle()处理组件实例的关系属性:$parent $children $root(访问根组件的属性和方法) $refs</li>
<li>initEvent()处理组件的自定义事件</li>
<li>initRender() 初始化插槽信息</li>
<li>callhook(‘beforeCreate’,vm):触发 beforeCreate 钩子函数</li>
<li>initState():初始化 data/props/methods/computed/watch</li>
<li>initInjection():初始化 inject 配置项</li>
<li>initProvide():初始化 provide 配置项</li>
<li>callhook(‘created’,vm):触发 created 钩子函数</li>
<li>触发$mount 进入挂载阶段</li>
</ol>
<p>这里还解决了一个问题:最早能拿到data和methods的钩子函数是哪个？<br>是created钩子函数;在beforeCreate前,只初始化了组件实例的关系属性,自定义事件,插槽信息等</p>

                
            </div>
            <hr/>

            



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/pride-blog/tags/Vue%E6%BA%90%E7%A0%81/">
                                    <span class="chip bg-color">Vue源码</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/share/css/share.min.css">
<div id="article-share">

    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/pride-blog/2021/061044298.html">
                    <div class="card-image">
                        
                        
                        <img src="/pride-blog/medias/featureimages/13.jpg" class="responsive-img" alt="Vue源码系列2-数据响应式原理">
                        
                        <span class="card-title">Vue源码系列2-数据响应式原理</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-06-10
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/pride-blog/categories/Vue%E6%BA%90%E7%A0%81/" class="post-category">
                                    Vue源码
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/pride-blog/tags/Vue%E6%BA%90%E7%A0%81/">
                        <span class="chip bg-color">Vue源码</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/pride-blog/2021/060733579.html">
                    <div class="card-image">
                        
                        
                        <img src="/pride-blog/medias/featureimages/21.jpg" class="responsive-img" alt="ES6-Set和weakSet">
                        
                        <span class="card-title">ES6-Set和weakSet</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-06-07
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/pride-blog/categories/ES6/" class="post-category">
                                    ES6
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/pride-blog/tags/ES6/">
                        <span class="chip bg-color">ES6</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/pride-blog/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/pride-blog/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/pride-blog/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/pride-blog/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/pride-blog/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2023</span>
            
            <span id="year">2021</span>
            <a href="/pride-blog/about" target="_blank">zihao xiong</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">














</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/pride-blog/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/pride-blog/libs/materialize/materialize.min.js"></script>
    <script src="/pride-blog/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/pride-blog/libs/aos/aos.js"></script>
    <script src="/pride-blog/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/pride-blog/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/pride-blog/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/pride-blog/libs/others/clicklove.js" async="async"></script>
    
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/pride-blog/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/pride-blog/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/pride-blog/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/pride-blog/libs/instantpage/instantpage.js" type="module"></script><!-- hexo-inject:begin --><!-- hexo-inject:end -->
    

</body>
<script src="./../source/js/cursor.js"></script>

</html>
